<?php
/**
 * Add a new Proffessional Experience
 *
 * @author Xavier VILAIN
 */
use Hive\Company;
use Fox\Core\Errors;
use Fox\Generator;
use Hive\Ressource;
use Hive\Ressource\Experience;
use Fox\Popup;
use Fox\Html\Screen;

$xview = Xview::instance();
$rid = $xview->val('rid');
$expid = $xview->val('jid');
/* @var $contact Hive\Ressource */
$contact = Xview::instance()->component("ressource", "object");
$experience = $contact->findExperiences("$expid:$rid");
$screen = new Screen("sJob","update",null,true,Generator::ajaxReload("contentCol",
			Generator::url("ressource","jobs",null,array("rid" => $rid))));
$block = $xview->component("ressource","job");
$screen->add($block)->noLegend();

$screen->buttons('update')->tabIndex = 9;
$screen->initialize($experience->getData());

if($screen->submitted()) {
	$fields = $screen->get();
	if(!$screen->errors()) {
		try {
			$jobtitle = $fields['jobtitle'];
			// Check if the Company Exist
			if(!empty($fields['companyName']))
			{
				$company = Company::lookup($fields['companyName']);
				if(!$company)
				{
					$company = new Company();
					$company->setFields(array("company_name" => $fields['companyName']));
					$company->create();
				}
				$fields['compid'] = $company->getId();
			}
			$experience->setFields($fields);
			$contact->replaceExperiences($experience);
			$start_date = null;
			// Update Current Experience Flag
			foreach($contact->experiences() as $experience) {
				$current = $experience->current;
				if($experience->start_date > $start_date ) {
					$start_date = $experience->start_date;
					$currentExperience = $experience;
				}
				if($current) {
					$oldCurrentExperience = $experience; 
				}
				
			}
			if($currentExperience->expid != $oldCurrentExperience->expid) {
				$oldCurrentExperience->current = 0;
				$contact->replaceExperiences($oldCurrentExperience);
				$currentExperience->current = 1;
				$contact->replaceExperiences($currentExperience);
			}
			$contact->prepareUpdate(Ressource::CHANGE_EXPERIENCES);
			$contact->update();
			Fox\Message::Success(Msg(\Fox\Msg::BUNDLE,\Fox\Msg::MSG_UPDATE,$jobtitle));
			echo $xview->messages(true,true);
			exit;
		}
		catch (Fox\Object\Exception\Save $e)
		{
			Errors::pushMessage($e);
		}
		catch (Fox\Object\Exception\NotExist $e)
		{
			Errors::pushMessage($e);
		}
	}
}
$popup = new Popup("add",Msg(Hive::BUNDLE,Hive::MSG_UPDATE_JOB),$screen,700);
echo $popup->display();